<script setup>
import { PlusOutlined } from '@ant-design/icons-vue';
import { message, Form } from 'ant-design-vue';
import { reactive, onMounted, toRaw, ref } from 'vue';
import { getDetailBook, getBookType, payChapter, editNovel,  finishBook} from '@/api/book/index.js';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '@/store/modules/user.js'
const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const bookModel = reactive({
  title: '',
  introduction: '',
  cover: '',
  classifyId: '',
  id: route.query.novelId
})
const payModel = reactive({
  amount: 0,
  chapterNo: 0,
  novelId: route.query.novelId
})
const rulesRef = reactive({
  title: [
    {
      required: true,
      message: '请填写书名',
    }
  ],
  classifyId: [
    {
      required: true,
      message: '请选择分类',
    }
  ],
  introduction: [
    {
      required: true,
      message: '请填写简介',
    }
  ],
})
const { validate, validateInfos } = Form.useForm(bookModel, rulesRef)
const bookState = reactive({
  bookType: [],
  imageUrl: '',
  loading: false,
  min: 0
})
const formItemLayout = {
  labelCol: {
    span: 4
  },
  wrapperCol: {
    span: 14
  }
}
const transformData = data => {
  return toRaw(data)
}
const isStatus = ref()
onMounted(
  getDetailBook({ id: route.query.novelId })
  .then(res => {
    bookModel.title = res.title
    bookModel.introduction = res.introduction
    bookModel.cover = res.cover
    bookState.imageUrl = res.cover
    bookModel.classifyId = res.classifyId
    isStatus.value = res.status
    payModel.amount = res.chargeAmount
    payModel.chapterNo = res.isCharge
  }),
  getBookType()
  .then(res => {
    bookState.bookType = res.map(item => ({ label: item.classifyName, value: item.id}))
  })
)

const handleCreate = () => {
  validate()
  .then(
    bookState.loading = true,
    editNovel(transformData(bookModel))
    .then(res => {
      message.success('修改成功')
      bookState.loading = false
    })
    .catch(err => {
      message.error(err || '修改失败')
    })
    .finally(
      bookState.loading = false
    )
  )
}
// 上传封面图
const handleChange = info => {
  if (info.file.status === 'done') {
    message.success(`${info.file.name} 上传成功`)
    bookState.imageUrl = info.file.response.data
    bookModel.cover = info.file.response.data 
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 上传失败`)
  }
}
const handlePay = () => {
  payChapter(toRaw(payModel))
    .then(() => {
      message.success('设置成功')
    })
    .catch((err) => {
      message.error(err || '设置失败')
    })
}
const handleEnd = () => {
  if (isStatus.value === 1) return message.error('操作失败, 该书已完结')
  finishBook({ id: route.query.novelId }).then(() => {
    message.success('操作成功')
    getDetailBook({ id: route.query.novelId })
    .then(res => {
      bookModel.title = res.title
      bookModel.introduction = res.introduction
      bookModel.cover = res.cover
      bookState.imageUrl = res.cover
      bookModel.classifyId = res.classifyId
      isStatus.value = res.status
    })
  }).catch(err => {
    message.error(err || '操作失败')
  })
}
</script>
<template>
<div class="book-info">
    <div class="form-box">
      <div class="cover">
        <a-upload
          name="file"
          list-type="picture-card"
          class="book-cover"
          :show-upload-list="false"
          :maxCount="1"
          action="http://localhost:9010/file/upload"
          @change="handleChange"
        >
          <img v-if="bookState.imageUrl" :src="bookState.imageUrl" class="avatar"/>
          <div v-else>
            <plus-outlined></plus-outlined>
            <div>上传封面</div>
          </div>
        </a-upload>
      </div>
      <a-form class="form" v-bind="formItemLayout">
        <a-form-item label="作品名称" v-bind="validateInfos.title">
          <a-input v-model:value="bookModel.title"></a-input>
        </a-form-item>
        <a-form-item label="分类" v-bind="validateInfos.classifyId">
          <a-select v-model:value="bookModel.classifyId" :options="bookState.bookType" />
        </a-form-item>
        <a-form-item label="简介" v-bind="validateInfos.introduction">
          <a-textarea :rows="4"  v-model:value="bookModel.introduction" placeholder="请填写相关简介" showCount/>
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 8, offset: 4 }">
          <a-button type="primary" :loading="bookState.loading" @click="handleCreate" shape="round" style="height: 40px;">确认修改</a-button>
        </a-form-item>
      </a-form>
    </div>
    <div class="pay" v-if="userStore.userInfo.isSign === 1">
      <div class="title">签约作者可设置收费金额：</div>
      <div class="pay-info">
        <span>开始收费章节:</span><a-input-number :min="1" v-model:value="payModel.chapterNo" class="input"></a-input-number>
        <span>收费金额:</span><a-input-number :min="0" v-model:value="payModel.amount" class="input"></a-input-number>
        <a-button type="primary" class="btn" shape="round" @click="handlePay">设置收费章节</a-button>
     </div>
    </div>
    <div class="pay" style="margin-top: 60px;" v-if="isStatus !== 1">
      <a-popconfirm
        title="请确认是否完结"
        ok-text="确认"
        cancel-text="取消"
        @confirm="handleEnd"
      >
        <a-button type="primary" style="width: 120px;" shape="round">完结小说</a-button>
      </a-popconfirm>
    </div>
</div>
</template>

<style lang="less" scoped>
.pay {
  margin-top: 50px;
  .title {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 20px;
  }
  .pay-info {
    span{
      margin: 0 15px;
    }
    .btn {
      margin-left: 30px;
    }
    .input {
      width: 120px;
      border-radius: 20px;
    }
  }
}
.wrapper {
  display:flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e7e7e7;
  padding-bottom: 20px;
  margin-top: 30px;
  .title {
    font-size: 16px;
    font-weight: 700;
    color: #222;
    line-height: 21px;
  }
}
.form-box {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  .cover {
    width: 200px;
    margin-right: 20px;
    .book-cover {
      width: 200px;
      height: 266px;
    }
    .avatar {
      width: 200px;
      height: 266px;     
    }
  }
  .form {
    flex: 1;
  }
}
</style>
<style lang="less">
.cover {
  .ant-upload.ant-upload-select-picture-card {
      width: 200px;
      height: 266px;
  }
}
</style>